package com.aiti.lulian.controller.crad;

import cn.hutool.core.util.StrUtil;
import com.aiti.base.core.base.controller.WebController;
import com.aiti.base.core.page.PageResult;
import com.aiti.base.core.utils.message.Message;
import com.aiti.lulian.annotates.AddGroup;
import com.aiti.lulian.annotates.EditGroup;
import com.aiti.lulian.annotates.QueryGroup;
import com.aiti.lulian.bo.CardClusterInfoBo;
import com.aiti.lulian.dto.CardClusterInfoDto;
import com.aiti.lulian.entity.LuLianEnterprise;
import com.aiti.lulian.entity.crad.cluster.CardClusterEnterpriseBinding;
import com.aiti.lulian.entity.crad.cluster.CardClusterInfo;
import com.aiti.lulian.entity.excel.CardClusterEnterpriseImport;
import com.aiti.lulian.entity.excel.CardVisitorRecordExport;
import com.aiti.lulian.handler.HeaderStyleHandler;
import com.aiti.lulian.service.ICardClusterEnterpriseImportService;
import com.aiti.lulian.service.ICardClusterInfoService;
import com.aiti.lulian.service.ILuLianEnterpriseUserService;
import com.aiti.lulian.vo.CardClusterDetailInfo;
import com.aiti.lulian.vo.CardClusterExportInfo;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;


@RestController
@RequestMapping("/card/cluster")
public class CardClusterInfoController extends WebController {

    private final ICardClusterInfoService baseService;

    private final ILuLianEnterpriseUserService enterpriseUserService;

    private final ICardClusterEnterpriseImportService cardClusterEnterpriseImportService;

    public CardClusterInfoController(ICardClusterInfoService baseService, ILuLianEnterpriseUserService enterpriseUserService, ICardClusterEnterpriseImportService cardClusterEnterpriseImportService) {
        this.baseService = baseService;
        this.enterpriseUserService = enterpriseUserService;
        this.cardClusterEnterpriseImportService = cardClusterEnterpriseImportService;
    }

    /**
     * 新增名片产业集群
     * @return 结果
     */
    @PostMapping("/addCardClusterInfo")
    public Message addCardClusterInfo(@Validated(value = {AddGroup.class}) @RequestBody CardClusterInfoBo bo){
        String userId = findUserId();
        //前置判断
        LuLianEnterprise luLianEnterprise = enterpriseUserService.selectCurrentUserJoinEnterpriseInfo(userId);
        if(luLianEnterprise == null || StringUtils.isBlank(luLianEnterprise.getBaseId())){
            return Message.fail("请先创建政府信息");
        }
        return Message.success(baseService.addCardClusterInfo(bo,userId,luLianEnterprise.getBaseId()));
    }

    @PostMapping("/updateCardClusterInfo")
    public Message updateCardClusterInfo(@Validated(value = {EditGroup.class}) @RequestBody CardClusterInfoBo bo){
        String userId = findUserId();
        bo.setBaseUpdateBy(userId);
        bo.setBaseCreateBy(userId);
        baseService.updateCardClusterInfo(bo);
        return Message.success();
    }

    /**
     * 查询产业集群的详情信息
     * @return
     */
    @GetMapping("/queryClusterDetailInfo")
    public Message queryClusterDetailInfo(@Validated(value = {QueryGroup.class})CardClusterInfoBo bo){
        String userId = bo.getUserId();
        if (StrUtil.isBlank(userId)) {
            userId = findUserId();
        }
        CardClusterDetailInfo cardClusterDetailInfo =  baseService.queryClusterDetailInfo(userId, bo);
        return Message.success(cardClusterDetailInfo);
    }

    @GetMapping("/queryClusterList")
    public Message queryClusterList(CardClusterInfoBo bo){

        Integer pageNum = bo.getPageNum();
        Integer pageSize = bo.getPageSize();

        String enterpriseId = bo.getEnterpriseId();
        if(StringUtils.isBlank(bo.getEnterpriseId())){
            String userId = findUserId();
            if(StringUtils.isBlank(userId)){
                return Message.fail("请登录");
            }
            LuLianEnterprise luLianEnterprise = enterpriseUserService.selectCurrentUserJoinEnterpriseInfo(userId);
            if(luLianEnterprise == null){
                return Message.fail("没有找到绑定的政府信息");
            }
            enterpriseId = luLianEnterprise.getBaseId();
        }

        bo.setEnterpriseId(enterpriseId);
        Page<CardClusterInfo> page = startPage(pageNum,pageSize);
        List<CardClusterInfo> list = baseService.queryClusterList(page,bo);
        return Success(getPageResult(list, pageNum, pageSize, (int) page.getTotal()));
    }

    @GetMapping("/selectEnterpriseInfoByClusterId")
    public Message selectEnterpriseInfoByClusterId(@RequestParam("clusterId") String clusterId){
        List<CardClusterEnterpriseBinding> cardClusterEnterpriseBindings = baseService.selectEnterpriseInfoByClusterId(clusterId);
        return Message.success(cardClusterEnterpriseBindings);
    }

    @PostMapping("/deleteClusterById")
    public Message deleteClusterById(@RequestBody CardClusterInfoBo bo){
        String userId = findUserId();
        return baseService.deleteClusterById(bo.getBaseId(),userId);
    }

    @ApiOperation("下载集群企业导入模板")
    @GetMapping("/enterprise/template/download")
    public Message downloadClusterEnterpriseTemplate(@RequestParam("userId") String userId,
                                            HttpServletResponse response) {
        FileInputStream fileInputStream = null;
        ServletOutputStream outputStream = null;
        try {
            if (StrUtil.isBlank(userId)) {
                return Fail("请先登录");
            }
            // 设置文件路径
            String filePath = "/mnt/service/lulian/file/集群企业导入模板.xlsx";
//            String filePath = "C:\\Users\\Administrator\\Desktop\\集群企业导入模板.xlsx";
            File downloadFile = new File(filePath);

            // 设置文件名（响应头中的推荐文件名）
            String fileName = "集群企业导入模板.xlsx";

            // 对文件名进行URL编码
            String encodedFileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");

            // 设置响应头
            response.setContentType("application/octet-stream");
//            response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
            response.setHeader("Content-Disposition", "attachment; filename=\"" + encodedFileName + "\"; filename*=UTF-8''" + encodedFileName);

            // 设置文件大小
            response.setContentLength((int) downloadFile.length());

            // 通过文件输入流读取文件内容
            fileInputStream = new FileInputStream(downloadFile);

            // 通过ServletOutputStream将文件内容写入HTTP响应
            outputStream = response.getOutputStream();
            byte[] buffer = new byte[4096];
            int bytesRead;

            while ((bytesRead = fileInputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }

            // 关闭流资源
            if (fileInputStream != null) {
                fileInputStream.close();
            }
            if (outputStream != null) {
                outputStream.close();
            }

            return Success();
        } catch (Exception e) {
            logger.error("下载模板异常：===》" + e);
            return Fail(e.getMessage());
        }
    }

    @ApiOperation("批量导入集群企业至暂存表")
    @PostMapping("/enterprise/import")
    public Message importClusterEnterpriseBatch(@RequestPart("file") MultipartFile file,
                                                @RequestParam("userId") String userId) {
        try {
            if (StrUtil.isBlank(userId)) {
                return Fail("请先登录");
            }
            if (file == null) {
                return Fail("请上传文件");
            }
            String contentType = file.getContentType();
            String originalFilename = file.getOriginalFilename();
            if (! ("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet".equals(contentType)
                    && originalFilename != null && originalFilename.endsWith(".xlsx"))) {
                return Fail("请上传xlsx格式的文件");
            }
            return baseService.importClusterEnterpriseBatch(file, userId);
        } catch (Exception e) {
            logger.error("导入异常：===》" + e);
            return Fail(e.getMessage());
        }
    }

    @ApiOperation("查询暂存表中的导入数据")
    @GetMapping("/enterprise/import/list")
    public Message getClusterEnterpriseImportList(@RequestParam("userId") String userId) {
        if (StrUtil.isBlank(userId)) {
            return Fail("请先登录");
        }
        List<CardClusterEnterpriseImport> list = cardClusterEnterpriseImportService.list(new LambdaQueryWrapper<CardClusterEnterpriseImport>()
                .orderByAsc(CardClusterEnterpriseImport::getSort));
        return Success(list);
    }

    @ApiOperation("删除暂存表中的导入数据")
    @DeleteMapping("/enterprise/import/remove")
    public Message removeClusterEnterpriseImport(@RequestParam("userId") String userId) {
        if (StrUtil.isBlank(userId)) {
            return Fail("请先登录");
        }
        cardClusterEnterpriseImportService.remove(null);
        return Success();
    }

    @GetMapping("/new/page")
    public Message clusterPage(CardClusterInfoDto dto){
        Page page = this.startPage();
        List<CardClusterDetailInfo> cardClusterDetailInfos = baseService.clusterPage(page, dto);
        return Message.success(getPageResult(cardClusterDetailInfos, dto.getPageNum(), dto.getPageSize(), page.getTotal()));
    }

    @PostMapping("/new/insert")
    public Message addCardClusterInfoNew(@Validated(value = {AddGroup.class}) @RequestBody CardClusterInfoBo bo){
        String userId = findUserId();
        return Message.success(baseService.addCardClusterInfoNew(bo,userId));
    }

    @PostMapping("/new/update")
    public Message updateCardClusterInfoNew(@Validated(value = {EditGroup.class}) @RequestBody CardClusterInfoBo bo){
        String userId = findUserId();
        bo.setBaseUpdateBy(userId);
        bo.setBaseCreateBy(userId);
        baseService.updateCardClusterInfoNew(bo);
        return Message.success();
    }

    /**
     * 查询产业集群的详情信息
     * @return
     */
    @GetMapping("/new/detail")
    public Message queryClusterDetailInfo(@RequestParam("baseId") String baseId){
        CardClusterDetailInfo cardClusterDetailInfo =  baseService.clusterDetailInfo(baseId);
        return Message.success(cardClusterDetailInfo);
    }

    @GetMapping("/new/export")
    public void clusterPage(HttpServletResponse response, CardClusterInfoDto dto) throws Exception {
        List<CardClusterExportInfo> cardClusterDetailInfos = baseService.clusterList(dto);// 设置响应头，确保浏览器以下载方式处理文件
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");

        // 设置文件名，注意需要对中文进行 URL 编码
        String fileName = URLEncoder.encode("产业数据列表", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileName + ".xlsx\";" + " filename*=UTF-8''" + fileName + ".xlsx");

        // 使用 EasyExcel 写入数据到输出流
        OutputStream outputStream =  response.getOutputStream();
        EasyExcel.write(outputStream, CardClusterExportInfo.class)
                .sheet("产业数据列表")
                .registerWriteHandler(new HeaderStyleHandler())
                .doWrite(cardClusterDetailInfos);

        // 关闭流资源
        if (outputStream != null) {
            outputStream.close();
        }

    }


    @ApiOperation("删除产业")
    @DeleteMapping("/new/delete")
    public Message delete(@RequestParam("baseId") String baseId) {
        return baseService.deleteClusterNew(baseId);

    }
}